package core

import (
	"bo.wang/st-chain/config"
	"fmt"
)

type Chain struct {
	difficulty int
	content    []*Block
}

func NewChain(genesis string, difficulty int) (chain *Chain) {
	chain = new(Chain)
	d := config.Public.Block.Difficulty // 默认的难度
	if difficulty != 0 {
		d = difficulty
	}
	chain.difficulty = d
	chain.content = []*Block{
		NewBlock(genesis, nil, d),
	}
	return
}

// 不允许单独操作区块，此处仅用于测试`Validate`方法
//func (chain *Chain) GetBlock(index int32) *Block {
//	return chain.content[index]
//}

func (chain *Chain) AddBlock(data string) {
	block := NewBlock(data, chain.content[len(chain.content)-1], chain.difficulty)
	chain.content = append(chain.content, block)
}

func (chain *Chain) Validate() (status ChainValidateStatus) {
	status = ValidatePassed
	for index, block := range chain.content {
		if !block.Validate() {
			status = ValidateTampering
		}
		if index > 0 { // 从第二个开始遍历
			previousBlock := chain.content[index-1]
			if block.GetPrevious() != previousBlock.hash { // hash
				status = ValidateBroken
			}
		}
	}
	return
}

func (chain *Chain) String() (result string) {
	result = fmt.Sprintf("Chain{\n\tdifficulty: %d\n\tcontent:", chain.difficulty)
	contentPart := "[\n"
	for _, block := range chain.content {
		contentPart += block.String() + "\n"
	}
	contentPart += "]}"
	result += contentPart
	return
}
